package cn.wowjoy.office.personal;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;

import javax.inject.Inject;

import cn.wowjoy.office.base.BaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.response.StaffListResponse;
import cn.wowjoy.office.loginnew.LoginActivity;
import cn.wowjoy.office.utils.PreferenceManager;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/10/19.
 */

public class PersonalViewModel extends NewBaseViewModel{

    @Inject
    ApiService mApiService;
    @Inject
    PreferenceManager preferenceManager;

    @Inject
    public PersonalViewModel(@NonNull NewMainApplication application) {
        super(application);
    }

    @Override
    public void onCreateViewModel() {

    }

    //获取员工信息
    public LiveData<LiveDataWrapper<StaffListResponse>> getStaffInfo(){
        final MediatorLiveData<LiveDataWrapper<StaffListResponse>> staffListResponse = new MediatorLiveData<>();
        staffListResponse.setValue(LiveDataWrapper.loading(null));
        Disposable disposable= mApiService.getStaffInfo("app")
                .flatMap(new ResultDataParse<StaffListResponse>())
                .compose(new RxSchedulerTransformer<StaffListResponse>())
                .subscribe(new Consumer<StaffListResponse>() {
                    @Override
                    public void accept(StaffListResponse staffResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        staffListResponse.setValue(LiveDataWrapper.success(staffResponse));

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        staffListResponse.setValue(LiveDataWrapper.error(throwable,null));

                    }
                });
        addDisposable(disposable);
        return staffListResponse;
    }

    public void logout(){
        preferenceManager.clearToken();
        LoginActivity.startAndClearTask(getApplication());
    }
}
